/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.singleton.exaple.多线程反序列化;

import java.io.*;

public class Singleton implements Serializable {
    /* private static Singleton instance = new Singleton();
     private Singleton(){}
     public static Singleton getInstance() {
         return instance;
     }*/

    /* 私有构造方法，防止被实例化 */
    private Singleton() {
    }

    /* 此处使用一个内部类来维护单例 */
    private static class SingletonFactory {
        private static  Singleton instance = new  Singleton();
    }

    /* 获取实例 */
    public static  Singleton getInstance() {
        return  Singleton.SingletonFactory.instance;
    }

    /* 如果该对象被用于序列化，可以保证对象在序列化前后保持一致 */
    public Object readResolve() {
        return getInstance();
    }
    public static void main(String[] args) {
         Singleton instance1 = Singleton.getInstance();
         Singleton instance2 = Singleton.getInstance();
         System.out.println("normal：" + (instance1 == instance2));
         try {
             //序列化
             File file = new File("src/main/java/com/azdebugit/moshi/test/learn/factory/method/t2/config2.xml");
             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
             oos.writeObject(instance1);
             oos.close();
             //反序列化
             ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
             Singleton instance3 = (Singleton) ois.readObject();
             System.out.println("deserialize：" + (instance1 == instance3));
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
 }